package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.MemberService;
import com.itheima.service.ReportService;
import com.itheima.service.SetmealService;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author LiangTianQi
 * @describe
 * @date 2020/11/21 17:56
 */
@RestController
@RequestMapping("/report")
public class ReportController {

    @Reference
    private MemberService memberService;

    @Reference
    private SetmealService setmealService;

    @Reference
    private ReportService reportService;

    /**
     * 统计会员的报表信息
     * @return
     */
    @GetMapping("/getMemberReport")
    public Result getMemberReport() {
        //通过当前时期，获取前一个年的月份
        LocalDate localDate = LocalDate.now();
        //将日期放入集合中
        List<String> months = new ArrayList<>();
        for (int i = 0; i < 12; i++) {
            localDate = localDate.plusMonths(-1);
            String format = localDate.format(DateTimeFormatter.ofPattern("yyyy.MM"));
            months.add(format);
        }
        Collections.reverse(months);
        try {
            //通过日期集合进行查询会员数量
            List<Integer> memberCounts = memberService.getCountByMonth(months);
            //将参数封装成map集合进行返回
            Map<String, Object> map = new HashMap<>();
            map.put("months", months);
            map.put("memberCounts", memberCounts);
            return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }


    @GetMapping("/getSetmealReport")
    public Result getSetmealReport() {
        try {
            //查询套餐名称，和每种套餐预定的数量
            List<Map<String, Object>> setmealCount = setmealService.getSetmealNameAndOrdercount();
            List<String> setmealNames = new ArrayList<>();
            for (Map<String, Object> stringObjectMap : setmealCount) {
                String name = (String) stringObjectMap.get("name");
                setmealNames.add(name);
            }

            Map<String, Object> map = new HashMap<>();
            map.put("setmealNames", setmealNames);
            map.put("setmealCount",setmealCount);
            return new Result(true,MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }

    @GetMapping("/getBusinessReportData")
    public Result getBusinessReportData() {
        try {
            Map<String, Object> map = reportService.getBusinessReport();
            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }


    /**
     * 将运营数据统计搞成xslx表下载
     */
    @GetMapping("/exportBusinessReport")
    public void exportBusinessReport(HttpServletRequest request, HttpServletResponse response) {
        //获取数据添加进excel中
        Map<String, Object> result = reportService.getBusinessReport();
        //取出返回结果数据，准备将报表数据写入到Excel文件中
        String reportDate = (String) result.get("reportDate");
        Integer todayNewMember = (Integer) result.get("todayNewMember");
        Integer totalMember = (Integer) result.get("totalMember");
        Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");
        Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");
        Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");
        Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");
        Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");
        Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");
        Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");
        Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");
        List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");

        //获取模板文件，文件在webapp中时使用getcontext。getrealpath，
        // 这时加载的文件是target/health_backend-1.0中，
        //文件在web-inf中的classes中时，用类加载器
        String s = this.getClass().getClassLoader().getResource("template").getPath() + File.separator + "report_template.xlsx";
//        String s = request.getSession().getServletContext().getRealPath("template")+ File.separator + "report_template.xlsx";
        System.out.println(s);
        XSSFWorkbook sheets =null;
        try {
            sheets = new XSSFWorkbook(new FileInputStream(new File(s)));
            XSSFSheet sheetAt = sheets.getSheetAt(0);
            //添加日期
            XSSFRow row = sheetAt.getRow(2);
            XSSFCell cell = row.getCell(5);
            cell.setCellValue(reportDate);
            //新增会员数
            row=sheetAt.getRow(4);
            row.getCell(5).setCellValue(todayNewMember);
            //总会员数
            row.getCell(7).setCellValue(totalMember);
            //本周新增
            row=sheetAt.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);
            //本月新增
            row.getCell(5).setCellValue(thisMonthNewMember);

            //今日预约、到诊
            row=sheetAt.getRow(7);
            row.getCell(5).setCellValue(thisWeekOrderNumber);
            row.getCell(7).setCellValue(todayVisitsNumber);

            //本周
            row=sheetAt.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);
            row.getCell(7).setCellValue(thisWeekVisitsNumber);
            //本月
            row=sheetAt.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);
            row.getCell(7).setCellValue(thisMonthVisitsNumber);

            //for循环添加热门套餐
            int num=12;
            for (Map map : hotSetmeal) {
                row=sheetAt.getRow(num);
                String name = (String) map.get("name");
                Long setmeal_count = (Long) map.get("setmeal_count");
                //数据库返回的小数的类型为BigDecimal
                BigDecimal proportion = (BigDecimal) map.get("proportion");
                row.getCell(4).setCellValue(name);
                row.getCell(5).setCellValue(setmeal_count);
                row.getCell(6).setCellValue(proportion.doubleValue());
                num++;
            }
            //设置两个下载的请求头
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition", "attachment;filename=report_data.xlsx");
            //将数据响应出去
            sheets.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (sheets!=null) {
                try {
                    sheets.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 将运营数据统计搞成xslx表下载
     */
    @GetMapping("/exportBusinessReport4PDF")
    public void exportBusinessReport4PDF(HttpServletRequest request, HttpServletResponse response) {
        //获取数据添加进excel中
        Map<String, Object> result = reportService.getBusinessReport();
        //取出返回结果数据，准备将报表数据写入到Excel文件中
        List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");

        //获取模板文件，文件在webapp中时使用getcontext。getrealpath，
        // 这时加载的文件是target/health_backend-1.0中，
        //文件在web-inf中的classes中时，用类加载器
        String jrxml = this.getClass().getClassLoader().getResource("template").getPath() + File.separator + "health_business3.jrxml";
        String jasper = this.getClass().getClassLoader().getResource("template").getPath() + File.separator + "health_business3.jasper";
        try {
            //编译模板
            JasperCompileManager.compileReportToFile(jrxml, jasper);
            //填充数据---使用JavaBean数据源方式填充
            JasperPrint jasperPrint =JasperFillManager.fillReport(jasper,result,
                                        new JRBeanCollectionDataSource(hotSetmeal));
            //设置两个下载的请求头
            response.setContentType("application/pdf");
            response.setHeader("content-Disposition", "attachment;filename=report.pdf");
            ServletOutputStream out = response.getOutputStream();
            JasperExportManager.exportReportToPdfStream(jasperPrint,out);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {

        }
    }

}
